package com.admission.service;

import java.util.Date;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.admission.model.Authority;
import com.admission.model.Employee;
import com.admission.model.Role;
import com.admission.util.OperatorDetails;
import com.google.common.collect.Sets;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * 演示扩展SpringSecurity的User类加入loginTime信息.
 * 
 * @author calvin
 */
@SuppressWarnings("deprecation")
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	private EmployeeManager employeeManager;

	/**
	 * 获取用户Detail信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		Employee employee = employeeManager.findByLoginName(username);
		if (employee == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}

		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(employee);

		boolean employeeNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean employeeNonLocked = true;

		OperatorDetails userDetails = new OperatorDetails(
				employee.getLoginName(), employee.getPassword(),
				employee.isLoginable(), employeeNonExpired,
				credentialsNonExpired, employeeNonLocked, grantedAuths);
		// 加入登录时间信息和用户角色
		userDetails.setEmployee(employee);
		userDetails.setLoginTime(new Date());
		userDetails.setRoleList(employee.getRoles());

		return userDetails;
	}

	/**
	 * 获得用户所有角色的权限.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(Employee employee) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : employee.getRoles()) {
			for (Authority authority : role.getAuthorities())
				authSet.add(new GrantedAuthorityImpl(authority
						.getPrefixedName()));
		}
		return authSet;
	}

	@Autowired
	public void setEmployeeManager(EmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}
}
